package com.dcivision.framework.web;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.bean.DmsLocMaster;
import com.dcivision.dms.dao.DmsLocMasterDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.bean.MtmEventMessageLog;
import com.dcivision.framework.dao.MtmEventMessageLogDAObject;

public class ListEventMessgeAction extends AbstractListAction {

  public static final String REVISION = "$Revision: 1.7 $";
  
  public ListEventMessgeAction(){
    this.setListName("eventMessageList");
  }
  
  public String getFunctionCode() {
    return SystemFunctionConstant.LOG_EVENT_MESSAGE;
  }

  public String getMajorDAOClassName() {
    return "com.dcivision.framework.dao.MtmEventMessageLogDAObject";
  }
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    ListEventMessageForm eventMessageForm = (ListEventMessageForm)form;
    log.debug("***************************** accessDateto:" + eventMessageForm.getAccessDateTo());
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    MtmEventMessageLogDAObject eventMessageDAO = new MtmEventMessageLogDAObject(sessionContainer,conn);
    String opMode = eventMessageForm.getOpMode();
    if ("clearAll".equals(opMode)){  	
    	List eventMessageList = eventMessageDAO.getList();    
    	if (eventMessageList.size()<1){
    		this.addError(request,"errors.eventlog.empty_Result");
    		eventMessageForm.setIsExport("");
    	}else{
    		try{
          if ("true".equals(eventMessageForm.getIsExport())){
            exportAllLog(mapping,eventMessageForm,request,response);
          }
          int total = eventMessageDAO.deleteAll();
          addMessage(request, MESSAGE_RECORDS_DELETED, "" + total);
          this.commit(request);
        }catch(ApplicationException e){
          this.rollback(request);
          this.handleApplicationException(request, e);
        }
        eventMessageForm.setOpMode("");
    	}
    } else if ("clear search result".equals(opMode)){
    	List eventMessageList  = eventMessageDAO.getListAll(eventMessageForm);
    	if (eventMessageList.size()<1){
    		this.addError(request,"errors.eventlog.empty_Result");
    		eventMessageForm.setIsExport("");
    	} else {
    		try{
          if ("true".equals(eventMessageForm.getIsExport())){
            exportSearchResultLog(mapping,eventMessageForm,request,response);
          }
          int total = eventMessageDAO.deleteAll(eventMessageForm);
          addMessage(request, MESSAGE_RECORDS_DELETED, "" + total);
          this.commit(request);
        }catch(ApplicationException e){
          this.rollback(request);
          this.handleApplicationException(request, e);
        }
    	}      
      eventMessageForm.setOpMode("");
    } 
    return super.execute(mapping,eventMessageForm,request,response);
  }
  
  public void getListData(ActionMapping mapping, AbstractSearchForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    log.debug("--------- get event list!");
    ListEventMessageForm eventForm = (ListEventMessageForm)form;
    List eventList = new ArrayList();
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    MtmEventMessageLogDAObject eventDAO = new MtmEventMessageLogDAObject(sessionContainer,conn);
    eventList = eventDAO.getMtmEventList(eventForm);
    request.setAttribute(this.m_sListName,eventList);
  }
  
  public void exportAllLog(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    MtmEventMessageLogDAObject eventMessageDAO = new MtmEventMessageLogDAObject(sessionContainer,conn);
    List eventMessageList = eventMessageDAO.getList();    
    this.exportLogExcel(request,eventMessageList);
  }

  public void exportSearchResultLog(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    ListEventMessageForm eventMessageForm = (ListEventMessageForm)form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    MtmEventMessageLogDAObject eventMessageDAO = new MtmEventMessageLogDAObject(sessionContainer,conn);
    List eventLogList = eventMessageDAO.getListAll(eventMessageForm);
    this.exportLogExcel(request,eventLogList);
  }
  
  /**
   * Creates a cell and aligns it a certain way.
   *
   * @param wb        the workbook
   * @param row       the row to create the cell in
   * @param column    the column number to create the cell in
   * @param align     the alignment for the cell.
   */
  private void createCell(HSSFWorkbook wb, HSSFRow row, short column,
                                 String value) {
    HSSFCell cell = row.createCell(column);
    cell.setEncoding(cell.ENCODING_UTF_16);
    cell.setCellValue(value);
  }
  
  private void exportLogExcel(HttpServletRequest request,List eventMessageList) {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
//    MtmEventMessageLogDAObject eventMessageDAO = new MtmEventMessageLogDAObject(sessionContainer,conn);
//    List eventMessageList = eventMessageDAO.getList();
    
    try {
      // creating excel file 
      HSSFWorkbook wb = new HSSFWorkbook();
      HSSFSheet sheet = wb.createSheet("Export Event log");
      sheet.setDefaultColumnWidth( (short) 24);
      short rowNum = 0;
      HSSFRow row = sheet.createRow(rowNum++); 
     
      //creating the first rows
      createCell(wb, row, (short) 0, MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "log.columnheader.event_type"));
      createCell(wb, row, (short) 1, MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "log.columnheader.event_date"));
      createCell(wb, row, (short) 2, MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "log.columnheader.event_time"));
      createCell(wb, row, (short) 3, MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "log.columnheader.event_source"));
      createCell(wb, row, (short) 4, MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "log.columnheader.event_message"));
      createCell(wb, row, (short) 5, MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "log.columnheader.event_error_code"));
      createCell(wb, row, (short) 6, MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "log.columnheader.event_action_taker"));
      createCell(wb, row, (short) 7, MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "log.columnheader.event_server"));
      createCell(wb, row, (short) 8, MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "log.columnheader.event_error_detail"));
      row = sheet.createRow(rowNum++);
      
      for (int j = 0;j < eventMessageList.size() ;j++){
        MtmEventMessageLog eventMessage = (MtmEventMessageLog)eventMessageList.get(j);
        createCell(wb, row, (short) 0, eventMessage.getEventType());
        createCell(wb, row, (short) 1, eventMessage.getDate());
        createCell(wb, row, (short) 2, eventMessage.getTime());
        createCell(wb, row, (short) 3, eventMessage.getSourceFunctionCode());
        createCell(wb, row, (short) 4, eventMessage.getMessage());
        createCell(wb, row, (short) 5, eventMessage.getMessageCode());
        createCell(wb, row, (short) 6, eventMessage.getActionTakerName());
        createCell(wb, row, (short) 7, eventMessage.getServerName());
        createCell(wb, row, (short) 8, eventMessage.getErrorDetail());
        row = sheet.createRow(rowNum++);
      }

      ByteArrayOutputStream byteOut = new ByteArrayOutputStream();      
      wb.write(byteOut); 
      
      DmsLocMasterDAObject locMasterDAO = new DmsLocMasterDAObject(sessionContainer, conn);
      DmsLocMaster locMaster = (DmsLocMaster) locMasterDAO.getObjectByID(new Integer(1));
      String locMasterPath = locMaster.getLocPath();
      
      byte[] excelData = byteOut.toByteArray();
      String path = locMasterPath+"/excel"+Math.random()+".xls";
      FileOutputStream f=new FileOutputStream(path);
      InputStream in = null;
      
      try {
        in = new ByteArrayInputStream(excelData);        
        int c;
        while ( (c = in.read()) != -1) {
          f.write(c);
        }
      } catch (Exception e) {
        log.error(e);
      } finally {
        try {
          in.close();
        } catch (Exception ignore) {} finally {
          in = null;
        }
        try {
          f.close();
        } catch (Exception ignore) {} finally {
          f = null;
        }
      }
      request.getSession().setAttribute("exlExportFileName",path );
      byteOut.close();
      sessionContainer = null;
      locMasterDAO = null;    
      
    }catch (Exception e) {
      log.error("export folder error.", e);
    }
  }
}
